// ajax
function my_ajax(options) {
    $.ajax({
        type: options.type == null ? "POST" : options.type,
        dataType: "json",
        data: options.data,
        contentType: options.contentType == null ? "application/json;charset=utf-8" : options.contentType,
        url: "http://120.55.165.31:8080/Elearning/api" + options.url,
        success: options.success,
        error: options.error == null ? function () {
            alert("ajax失败");
        } : options.error,
        async: options.async == null ? false : options.async
    });
}

// 添加鼠标进入移除事件
$(".chapter").on("mouseenter", "li", function() {
    $(this).find("button").css("display", "block");
});
$(".chapter").on("mouseleave", "li", function() {
    $(this).find("button").css("display", "none");
});

// 返回传入该页面的数据
function getParameters(){
    let courseId = location.search.split("=")[1];
    // 测试用的token 实际上token需要从会话存储中提取
    //let token = localStorage.getItem("token");
    let token = null;
    my_ajax({
        data:JSON.stringify({ username:"user", password:"123456"}),
        url: "/all/user/login",
        success: function (response) {
            token = response.data.token;
        }
    });
    let parameters = {
        courseid : courseId,
        token : token
    };
    return parameters;
}

// 根据token获取用户信息
function getUserInfo(){
    let userInfo = null;
    let token = JSON.stringify({token:getParameters().token});
    token = token.replace('"token":', '"token": ');
    my_ajax({
        data:token,
        url: "/user/user/getUserCurrent",
        success: function (response) {
            userInfo = response.data;
        }
    });
    return userInfo;
}

// 根据传入的参数获取课程相关信息并初始化界面
$(document).ready(function () {
    let courseId = getParameters().courseid;
    let courseInformation = getCourseInfo(courseId);
    setHtml(courseInformation);
    let chapters = getChapters(courseId);
    setChapterList(chapters.chapters);
    let userInfo = getUserInfo();
    if (isJoin())
    {
        $(".my-comment").show();
        $(".my-comment").children("img").attr("src", "http://120.55.165.31:8080/Elearning/" + userInfo.userImage);
        $(".my-comment").children("h6").text(userInfo.username);
    }else{
        $(".try-button").css("display", "inline");
        $(".purchase-button").css("display", "inline");
    }

    let comments = getCourseComment(courseId);
    setComment(comments);
});

// 获取课程信息
function getCourseInfo(CourseID) {
    let course = null;
    let options = {
        data:JSON.stringify({courseId : CourseID}),
        url:"/all/course/selectCourseByCourseId",
        success:function (data) {
            course = data.data;
        }
    };
    my_ajax(options);
    return course;
}

// 设置课程信息界面
function setHtml (course){
    $(".course-name").html(course.courseName);
    $(".course-img").attr("src", "http://120.55.165.31:8080/Elearning/" + course.courseImage);
    $(".teacher-name").parent().append(course.teacherName);
    $(".learn-total").parent().append(course.learnTotal);
    $(".course-create-date").parent().append(course.courseTime.substring(0,10));
    $(".purchase-button>i").text(course.cost);
    $(".teacher-intro").text(course.teacherIntroduction);
    $(".course-intro").text(course.courseIntroduction);

}

// 获取课程章节
function getChapters(CourseID) {
    let data = null;
    let options = {
        data:JSON.stringify({courseId : CourseID, page:1, number:10000}),
        url:"/all/chapter/selectChapterByCourseId",
        success:function (response) {
            data = response.data;
        }
    };
    my_ajax(options);
    return data;
}

// 设置课程章节列表
function setChapterList(chapters) {
    let chapterHtml = "";
    for(let chapter of chapters)
    {
        chapterHtml += '<li>\n' +
            '                    <a href="#?chapterId=" ' + chapter.chapterId + '>\n' +
            '                        <i class="fa fa-play-circle fa-lg" aria-hidden="true"></i>\n' +
            '                        <p>'+ chapter.chapterName + '</p>\n' +
            '                        <button>开始学习</button>\n' +
            '                    </a>\n' +
            '                </li>'
    }
    $(".chapter>ul").html(chapterHtml);
}

// 判断是否有参加该课程
function isJoin() {
    let data = null;
    let options = {
        data:JSON.stringify({courseId : getParameters().courseid, token : getParameters().token}),
        url:"/user/learn/selectLearnByCourseIdAndUserId",
        success:function (response) {
            data = response;
        }
    };
    options.data = options.data.replace('"token":','"token": ');
    my_ajax(options);

    return data.status !== 501;
}

// 获取课程评论
function getCourseComment(cID){
    let data = null;
    let options = {
        data:JSON.stringify({courseId : cID, page:1, number:10000}),
        url:"/all/learn/selectCourseComment",
        success:function (response) {
            data = response.data;
        }
    };
    my_ajax(options);
    return data;
}

// 设置课程评论列表
function setComment(data){
    let total = data.total;
    let comments = data.comments;
    for(let i = 0; i < total; i++)
    {
        $("#CommentArea").html("<div class=\"col-lg-4\" style=\"margin-left: 20px; margin-top: 10px\">\n" +
            "                    <img src=\"http://120.55.165.31:8080/Elearning/" + comments[i].userImage + "\">\n" +
            "                    <h6>"+ comments[i].username + "</h6>\n" +
            "                    <h6>" + comments[i].courseCommentTime + "</h6>\n" +
            "                </div>\n" +
            "                <div class=\"col-lg-7\">\n" +
            "                    <p class=\"auto-wrap\"> " + comments[i].courseComment + " </p>\n" +
            "                </div>\n" +
            "                   <hr/>");
    }
}

// 发送评论 底层接口
function sendComment(comment){
    let options = {
        data:JSON.stringify({courseId : getParameters().courseid, courseStar : 5, courseComment : comment,
            courseCommentTime : getTime(), token : getParameters().token}),
        url:"/user/learn/updateCourseComment",
        success:function (response) {
            console.log(response);
        }
    };
    options.data = options.data.replace('"token":','"token": ');
    my_ajax(options);
}

// 获取当前时间
function getTime() {
    let date = new Date();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    if (month <= 9)
        month = "0" + month;
    if (strDate <= 9)
        strDate = "0" + strDate;
    if(hour <= 9)
        hour = "0" + hour;
    if(minute <= 9)
        minute = "0" + minute;
    if(second <= 9)
        second = "0" + second;
    let currentDate = date.getFullYear() + "-" + month + "-" + strDate
        + " " + hour + ":" + minute + ":" + second;
    return currentDate;
}

// 发表评论
function postComment() {
    let text = $("textarea").val();
    if (text.length === 0) {
        alert("评论输入不能为空");
        return;
    }
    sendComment(text);
    let courseId = getParameters().courseid;
    let comments = getCourseComment(courseId);
    setComment(comments);
    $("textarea").val("");
}

// 参加课程
function joinCourse(){
    placeOrder();
    $(".try-button").css("display", "none");
    $(".purchase-button").css("display", "none");
}

// 下单
function placeOrder() {
    let options = {
        data:JSON.stringify({courseId : getParameters().courseid, token : getParameters().token, orderState : "0"}),
        url:"/user/learn/addLearn",
        success:function (response) {
            console.log(response);
        }
    };
    options.data = options.data.replace('"token":','"token": ');
    my_ajax(options);
}

